package com.captain.special.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/4/3 22:56
 */
public class 交换链表中的节点1721 {
    public static void main(String[] args) {
        new 交换链表中的节点1721().swapNodes(ListNode.getInstance(), 2);
    }

    public ListNode swapNodes(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        ListNode curLen = head;
        int len = 0;
        while (curLen != null) {
            len++;
            curLen = curLen.next;
        }
        // 5 - 2 + 1
        ListNode cur = head;
        int index = 1;
        int back;
        back = len - k + 1;
        if (back < k) {
            int tpValue = k;
            k = back;
            back = tpValue;
        }
        // 5 - 2 + 1= 4
        //
        //7,9,6,6,7
        ListNode temp = null;
        while (cur != null) {
            if (index == k) {
                temp = cur;
            }
            if (index == back) {
                //交换值
                int tpValue = temp.val;
                temp.val = cur.val;
                cur.val = tpValue;
            }
            cur = cur.next;
            index++;
        }
        return head;
    }
}
